package com.shawn.baseappbygroovydsl.spf

import android.content.Context
import android.content.SharedPreferences
import com.shawn.baseappbygroovydsl.base.AppBase

/**
 * @author Afra55
 * @date 4/13/21
 * A smile is the best business card.
 *
var isNotOrganic:Boolean
get() = getBooleanValue("isNotOrganic", false)
set(value) = setValue("isNotOrganic", value)
 */
open class BaseSp(val name: String = "Clear") {

    private fun sp(): SharedPreferences? {
        return AppBase.instance.getSharedPreferences(name, Context.MODE_PRIVATE)
    }

    fun setValue(key: String, any: Any) {
        sp()?.let {
            val edit = it.edit()
            when (any) {
                is String -> edit.putString(key, any)
                is Boolean -> edit.putBoolean(key, any)
                is Int -> edit.putInt(key, any)
                is Long -> edit.putLong(key, any)
                is Float -> edit.putFloat(key, any)
                else -> {
                    edit.putString(key, any.toString())
                }
            }
            edit.apply()
        }
    }

    fun getBooleanValue(key: String, default: Boolean): Boolean {
        return sp()?.getBoolean(key, default) ?: default
    }

    fun getStringValue(key: String, default: String? = ""): String? {
        return sp()?.getString(key, default) ?: default
    }

    fun getIntValue(key: String, default: Int): Int {
        return sp()?.getInt(key, default) ?: default
    }

    fun getLongValue(key: String, default: Long): Long {
        return sp()?.getLong(key, default) ?: default
    }

    fun getFloatValue(key: String, default: Float): Float {
        return sp()?.getFloat(key, default) ?: default
    }

    fun clearAll() {
        sp()?.edit()?.clear()?.apply()
    }

    fun getAll(): Map<String, *>? {
        return try {
            sp()?.all
        } catch (e: Exception) {
            null
        }
    }

}